<template>
  <div class="fullMain" style="max-height: calc(100% - 50px);overflow: scroll;">
    <div style="position:fixed; width:100%; z-index:999">
      <x-header
        :left-options="{backText: '',showBack: false}"
        :right-options="{showMore: true}"
        @on-click-more="showMenusOfCreateAndJoin = true"
      >{{groupTitle}}</x-header>
    </div>
    <div style="height: 55px" />
    <div v-transfer-dom>
      <actionsheet
        :menus="groupActions"
        @on-click-menu="selectGroupAction"
        v-model="showMenusOfCreateAndJoin"
        show-cancel
      ></actionsheet>
    </div>
    <!--插入加入群的弹窗-->
    <EnterGroupG :isShowEnterGroup.sync="isShowEnterGroup"></EnterGroupG>
    <!--插入验证提示框-->
    <div v-transfer-dom>
      <alert v-model="isShowAlert">{{alertText}}</alert>
    </div>
    <!-- 创建群 -->
    <CreateGroup :isShowCreate.sync="isShowCreate"></CreateGroup>
    <!-- 底部导航栏 -->
    <NavigationOfReport :flagOfItem.sync="flagOfItem"></NavigationOfReport>

    <div class="mainbBg">
      <search
        @result-click="toGroupMemberPage"
        @on-change="searchResultFun"
        v-model="searchCondition"
        placeholder="请输入关键字进行搜索"
        position="absolute"
        auto-scroll-to-top
        top="46px"
        @on-cancel="onCancelSearch"
        @on-submit="searchResultFun"
        ref="search"
      ></search>

      <panel :list="searchResult" v-show="showSearchResult" @on-click-item="toGroupMemberPage"></panel>
      <panel
        :list="allGroupListForDisplay"
        type="2"
        v-show="showAllGroup"
        @on-click-item="toGroupMemberPage"
      ></panel>
    </div>
  </div>
</template>

<script>
import { XHeader, Actionsheet, TransferDom, Panel, Search, Divider } from "vux";
import { XInput } from "vux";
import { PopupPicker } from "vux";
import EnterGroupG from "components/EnterGroup/EnterGroupG.vue";
import CreateGroup from "components/CreateGroup2/CreateGroup.vue";
import { mapState } from "Vuex";
import { compareByProp } from "utilMethods/sort.js";
import group from "api/group";
import NavigationOfReport from "components/Navigation/NavigationOfReport.vue";

export default {
  name: "U_group",
  components: {
    XHeader,
    XInput,
    PopupPicker,
    EnterGroupG,
    CreateGroup,
    NavigationOfReport,
    Actionsheet,
    Panel,
    Search,
    Divider
  },
  data() {
    return {
      ssTitle: "",
      ssValue: [],
      tjP: "搜索",
      showMenusOfCreateAndJoin: false,
      isShowEnter: false,
      isShowEnterGroup: false,
      isShowEnterLab: false,
      alertText: "",
      isShowAlert: false,
      allGroupList: [],
      allGroupListForDisplay: [],
      isShowCreate: false,
      allGroupListAdmin: [],
      isShowGroupManage: true, //是否展示管理的群
      isShowGroupEnter: true, //是否展示加入的群
      flagOfItem: "group",
      groupActions: {
        create: "新建群",
        join: "加入群"
      },
      groupTitle: "我的群组",
      searchResult: [], //存放搜索的结果
      showSearchResult: false, //控制显示搜索结果的panel
      showAllGroup: true,
      searchCondition: "" //搜索条件
    };
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo
    })
  },
  mounted() {
    this.getAllGroups();
  },
  directives: {
    TransferDom
  },
  watch: {
    isShowEnter(val) {
      this.getAllGroups();
    },
    isShowEnterGroup(val) {
      this.getAllGroups();
    },
    searchCondition(val) {
      if (val === null || val === "") {
        this.showAllGroup = true;
        this.showSearchResult = false;
      } else {
        this.showAllGroup = false;
        this.showSearchResult = true;
      }
    }
  },
  methods: {
    back() {
      this.$router.go(-1);
    },
    showAlert(alertText) {
      this.isShowAlert = true;
      this.alertText = alertText;
    },
    closeTip() {
      this.isShowAlert = false;
      this.alertText = "";
    },
    joinGroupG() {
      this.isShowEnterGroup = true;
    },
    selectGroupAction(value) {
      console.log(value);
      if ("create" === value) {
        this.isShowCreate = true;
        this.isShowEnterGroup = false;
        this.groupTitle = "创建群组";
      }
      if ("join" === value) {
        this.isShowEnterGroup = true;
        this.isShowCreate = false;
        this.groupTitle = "加入群组";
      }
      if ("cancel" === value) {
        this.isShowCreate = false;
        this.isShowEnterGroup = false;
        this.groupTitle = "我的群组";
      }
    },
    toGroupMemberPage(item) {
      console.log("item", item);
      if (this.showSearchResult) {
        item = item.other;
      }
      console.log(item);
      if (item.userTypeInGroup === 0) {
        this.$store.commit("stageIsGroupOwner", true);
      } else if (item.userTypeInGroup === 1) {
        this.$store.commit("stageIsGroupAdmin", true);
      } else {
        this.$store.commit("stageIsGroupOwner", false);
        this.$store.commit("stageIsGroupAdmin", false);
      }
      this.$store.commit("recordGroupPresent", item.groupInfo);
      if (item.groupInfo.groupId === 887) {
        this.saveMemberNameAndId(item.groupInfo.groupId);
      } else {
        this.$router.push({ name: "G_group_member" });
      }
    },
    async getAllGroups() {
      const result = await group.getGroupsBeIn();
      if (result.code === 0) {
        this.showAlert("查询失败，请重试。");
      } else {
        this.allGroupList = result.data;
        console.log(this.allGroupList);
        // this.allGroupList.sort(compareByProp('detail groupName'))
        this.allGroupList.forEach(element => {
          if (element.detail.groupName !== null) {
            let groupForDisplay = {
              title:
                element.detail.groupName.slice(
                  element.detail.groupName.lastIndexOf("-") + 1
                ) +
                "（" +
                this.judgeUserTypeInGroup(element, this.userInfo.userId).desc +
                "）",
              desc: element.detail.groupName,
              userTypeInGroup: this.judgeUserTypeInGroup(
                element,
                this.userInfo.userId
              ).type,
              groupInfo: element
            };
            this.allGroupListForDisplay.push(groupForDisplay);
          }
        });
      }
    },
    judgeUserTypeInGroup(groupInfo, userId) {
      let userTypeInGroup = {};
      if (userId === groupInfo.detail.ownerId) {
        userTypeInGroup = { type: 0, desc: "群主" };
      } else if (groupInfo.detail.adminList.includes(userId)) {
        userTypeInGroup = { type: 1, desc: "管理员" };
      } else {
        userTypeInGroup = { type: 2, desc: "普通群成员" };
      }
      return userTypeInGroup;
    },

    showOrNot(param) {
      if (param === "manage") {
        this.isShowGroupManage = !this.isShowGroupManage;
      } else {
        this.isShowGroupEnter = !this.isShowGroupEnter;
      }
    },
    searchResultFun() {
      this.searchResult = [];
      console.log("结果范围", this.allGroupListForDisplay);
      for (let i = 0; i < this.allGroupListForDisplay.length; i++) {
        const s =
          this.allGroupListForDisplay[i].title +
          this.allGroupListForDisplay[i].desc;
        if (s.match(this.searchCondition)) {
          console.log("匹配");
          this.searchResult.push({
            title: this.allGroupListForDisplay[i].title,
            desc: this.allGroupListForDisplay[i].desc,
            other: this.allGroupListForDisplay[i]
          });
        }
      }
      if (this.searchResult.length) {
      }
      console.log("搜索结果", this.searchResult);
      return this.searchResult;
    },
    onCancelSearch() {
      this.searchResult = [];
      console.log("退出搜索");
    },
    async saveMemberNameAndId(groupId) {
      const result = await group.getInfoOfMembers({ groupId: groupId });
      console.log("群信息", result);
      if (result.code === 1) {
        let nameMap = [];
        result.data.forEach(item => {
          const mapItem = {
            id: item.userId,
            name: item.detail.name,
            avatar: item.detail.avatar
          };
          nameMap.push(mapItem);
        });
        this.$store.commit("stageMemberMap", nameMap);
        console.log("store中的群名单", this.$store.state.memberMap);
        this.$router.push("chat/G_group_chat");
      } else {
        this.showAlert("获取群信息失败，请稍后再试");
      }
    }
  }
};
</script>
<style>
</style>
